package edu.ccut.saturn.manager.bundles.core;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import edu.ccut.saturn.component.ComponentManager;
import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IBundleComponentInfo;
import edu.ccut.saturn.component.IComponentInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnDataManager;
import edu.ccut.saturn.component.impl.SaturnActionComponentInfo;
import edu.ccut.saturn.component.impl.SaturnBaseComponentInfo;
import edu.ccut.saturn.component.impl.SaturnLogicComponentInfo;

public class GetComponentTree extends DefaultComponent {

	private static final String IMAGE_PATH = "component/";

	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		//bundle名
		String key = (String) parameterContext.getParameterValue(0);
		//取组件文件结构（component,logic,action）
		IBundleComponentInfo bundleComponentInfo = ComponentManager
				.getInstance().getBundleComponentInfo(key);

		List<String> componentStringList = new ArrayList<String>();
		String type = "";

		if (bundleComponentInfo != null) {
			Collection<IComponentInfo> componentInfos = bundleComponentInfo
					.getComponentInfos();

			Iterator<IComponentInfo> componentIterator = componentInfos
					.iterator();

			while (componentIterator.hasNext()) {
				IComponentInfo componentInfo = componentIterator.next();

				if (componentInfo instanceof SaturnActionComponentInfo) {
					type = "action_saturnfolder";

				} else if (componentInfo instanceof SaturnLogicComponentInfo) {
					type = "logic_saturnfolder";

				} else if (componentInfo instanceof SaturnBaseComponentInfo) {
					type = "component_saturnfolder";

//				} else if (componentInfo instanceof SaturnDataInfo) {
//					type = "data_saturnfolder";
//
//				} else if (componentInfo instanceof SaturnValidateInfo) {
//					type = "validate_saturnfolder";
//
//				} else if (componentInfo instanceof SaturnWorkFlowInfo) {
//					type = "workflow_saturnfolder";
				}
                //形如 /userModule/userLogic/Account.logic
				String componentKey = componentInfo.getKey();
				//形如 /userModule/userLogic
				String componentString = componentKey.substring(0, componentKey
						.lastIndexOf("/"));

				if (componentString.lastIndexOf("/") > 0) {
					type = "module";
					                       //形如 userModule,module
					componentStringList.add(componentString.substring(0,
							componentString.lastIndexOf("/")).replace("/", "")
							+ "," + type);

				} else {
					                       //形如 userLogic,logic_saturnfolder
					componentStringList.add(componentString.replace("/", "")
							+ "," + type);
				}
			}
		}
		//componentStringList内容形如 
		//userModule,module, 
		//userModule,module,  
		//roleModule,module, 
		//userModule,module, 
		//roleModule,module, 
		//userModule,module, 
		//userModule,module
        //取数据项文件结构(saturnData)
		Set<String> saturnDataNamespaceKeys = SaturnDataManager.getInstance()
				.getSaturnDataInfoNamespaceKeys();// data

		if (saturnDataNamespaceKeys != null) {
			for(String saturnDataNameSpaceKey :saturnDataNamespaceKeys){
				//namespace形如 http://saturnManager/dictModule/data
				String[] keyArray = saturnDataNameSpaceKey.substring(7).split(
				"/");
				String bundleName = keyArray[0];
				//只选择当前bundle下的数据项显示
				if (key.equals(bundleName)) {
		
					if (keyArray.length == 2) {
						type = "data_saturnfolder";
		
					} else if (keyArray.length == 3) {
						type = "module";
					}
					componentStringList.add(keyArray[1] + "," + type);
				}
			}
		}

		componentStringList = unique(componentStringList);
		String treeXml = getTreeXml(componentStringList);
		parameterContext.setParameter(1, treeXml);
		
		
		List<Map> result = new ArrayList<Map>();
		
		for(String str : componentStringList){
			String text = str.split(",")[0];
			//String type = str.split(",")[1];
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", text);
			map.put("text", text);
			map.put("icon", "images/module.gif");
			//map.put("key", "edu.ccut.saturn.manager.bundles.impl");
			//map.put("type", type );
			result.add(map);
		}
		
		
		parameterContext.setParameter(2, result);//输出一个list 转json用
	}

	public String getTreeXml(List<String> list) {
		Collections.sort(list);
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer
				.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><tree id=\"0\">"); //$NON-NLS-1$

		stringBuffer.append("<item text=\"").append("src").append("\" id=\"")
				.append("src").append("\"").append(" im0=\"zzjgs1.gif\"")
				.append(" open=\"1\">");

		for (String nameStr : list) {
			String[] nameAndType = nameStr.split(",");
			stringBuffer.append("<item text=\"").append(nameAndType[0]).append(
					"\" id=\"").append(nameAndType[0]).append("\"").append(
					" im0=\"" + IMAGE_PATH + nameAndType[1] + ".gif\" im1=\""
							+ IMAGE_PATH + nameAndType[1] + ".gif\" im2=\""
							+ IMAGE_PATH + nameAndType[1] + ".gif\"").append(
					" child=\"1\" >").append("</item>");
		}
		stringBuffer.append("</item>");
		stringBuffer.append("</tree>");
		String treeXml = stringBuffer.toString();
		return treeXml;
	}

	/**
	 * 去掉list中的重复项
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<String> unique(List<String> list) {
		Set set = new HashSet();
		set.addAll(list);

		List list1 = new ArrayList();
		list1.addAll(set);

		return list1;
	}
	/*
	 * private List<Map<String, Object>> getRoot( Collection<IComponentInfo>
	 * componentInfos) { Iterator<IComponentInfo> componentIterator =
	 * componentInfos.iterator(); List<Map<String, Object>> list = new
	 * ArrayList<Map<String, Object>>();
	 * 
	 * while (componentIterator.hasNext()) { IComponentInfo componentInfo =
	 * componentIterator.next(); String componentKey = componentInfo.getKey();
	 * String componentString = componentKey.substring(0, componentKey
	 * .lastIndexOf("/")); String name; if (componentString.lastIndexOf("/") >
	 * 0) { name = componentString.substring(0,
	 * componentString.lastIndexOf("/")).replace("/", ""); } else { name =
	 * componentString.replace("/", ""); } if (list.size() == 0) { Map<String,
	 * Object> map = new HashMap<String, Object>();
	 * 
	 * String path = null; int level = 1; String parent_id = null; String key;
	 * 
	 * key = "/" + name; map.put("id", key); map.put("name", name);
	 * map.put("path", path); map.put("level", level); map.put("parent_id",
	 * parent_id); list.add(map); getRootNext(componentInfos, map, list); }
	 * boolean flag = true; for (Map<String, Object> map1 : list) {
	 * 
	 * if (map1.get("name").equals(name)) { flag = false; } } if (flag) { Map<String,
	 * Object> map = new HashMap<String, Object>();
	 * 
	 * String path = null; int level = 1; String parent_id = null; String key;
	 * 
	 * key = "/" + name; map.put("id", key); map.put("name", name);
	 * map.put("path", path); map.put("level", level); map.put("parent_id",
	 * parent_id); list.add(map); getRootNext(componentInfos, map, list); } }
	 * return list; }
	 * 
	 * private void getRootNext(Collection<IComponentInfo> componentInfos, Map<String,
	 * Object> parentNode, List<Map<String, Object>> treeList) {
	 * 
	 * for (IComponentInfo conponentInfoItem : componentInfos) { // 有两种情况 //
	 * 1子节点是文件 2子节点是文件夹 String itemKey = conponentInfoItem.getKey(); // String
	 * parentName = (String)parentNode.get("name"); int parentLevel = (Integer)
	 * parentNode.get("level"); // 根据父节点层数查找子节点 String[] itemKeyPart =
	 * itemKey.split("/"); if (((String) parentNode.get("name"))
	 * .equals(itemKeyPart[parentLevel])) { // conponentInfoItem 是 parentNode
	 * 的子节点 Map<String, Object> map = new HashMap<String, Object>(); String
	 * name = itemKeyPart[parentLevel + 1]; if (!checkNameExist(treeList,
	 * parentNode.get("id") + "/" + name)) { String path = null; if
	 * (name.split("\\.").length > 1) { // 是文件 给path赋值 } map.put("id",
	 * parentNode.get("id") + "/" + name); map.put("name", name);
	 * map.put("path", path); map.put("level", parentLevel + 1);
	 * map.put("parent_id", parentNode.get("id")); treeList.add(map); if
	 * (name.split("\\.").length == 1) { // 是文件夹 查找子节点
	 * getRootNext(componentInfos, map, treeList); } } } } }
	 * 
	 * 
	 * private boolean checkNameExist(List<Map<String, Object>> treeList,
	 * String id) { for (Map<String, Object> map : treeList) { if
	 * (map.get("id").equals(id)) { return true; } } return false; }
	 * 
	 * private List<Map<String, Object>> getTreeList( Collection<IComponentInfo>
	 * IComponentInfos) { List<Map<String, Object>> bundleTreeList = new
	 * ArrayList<Map<String, Object>>();
	 * 
	 * Iterator<IComponentInfo> componentIterator = IComponentInfos.iterator();
	 * 
	 * while (componentIterator.hasNext()) { IComponentInfo componentInfo =
	 * componentIterator.next();
	 * 
	 * bundleTreeList.add(this.obtainModuleLevelMap(componentInfo));
	 * bundleTreeList.add(this.obtainModuleNextLevelMap(componentInfo));
	 * bundleTreeList.add(this.obtainComponentLevelMap(componentInfo)); } //
	 * bundleTreeList = this.unique(bundleTreeList); return bundleTreeList; } /*
	 * private List<Map<String, Object>> obtainTreeList( IComponentInfo
	 * componentInfo) { List<Map<String, Object>> bundleTreeList = new
	 * ArrayList<Map<String, Object>>();
	 * 
	 * Map<String, Object> treeModuleMap = this
	 * .obtainModuleLevelMap(componentInfo); Map<String, Object>
	 * treeModuleNextMap = this .obtainModuleNextLevelMap(componentInfo); Map<String,
	 * Object> treeComponentMap = this .obtainComponentLevelMap(componentInfo);
	 * 
	 * bundleTreeList.add(treeModuleMap); bundleTreeList.add(treeModuleNextMap);
	 * bundleTreeList.add(treeComponentMap);
	 * 
	 * return bundleTreeList; }
	 */

}
